package com.py.credit.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

/**
 * 文件处理工具类
 * 
 * @author Leegern
 * @date 2018年3月6日
 */
public class FileUtils {

	/** 字符集：UTF-8 **/
	public static final String CHARSET_UTF8 = "UTF-8";

	/** 文件后缀名：word **/
	public static final String SUFFIX_WORD = ".docx";

	/** 文件分隔符 **/
	public static final String FILE_SEPARATOR = "/";

	/**
	 * 获取web应用根目录路径
	 * 
	 * @return
	 */
	public static String getWebRootPath() {
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		if (null == classLoader) {
			classLoader = ClassLoader.getSystemClassLoader();
		}
		java.net.URL url = classLoader.getResource("");
		String rootClassPath = url.getPath() + FILE_SEPARATOR;
		File rootFile = new File(rootClassPath);
		String webInfoPath = rootFile.getParent() + FILE_SEPARATOR;
		File webInfoDir = new File(webInfoPath);
		String webRootPath = webInfoDir.getParent() + FILE_SEPARATOR;
		return webRootPath;
	}

	/**
	 * 流输出
	 * 
	 * @param is
	 *            输入流
	 * @param os
	 *            输出流
	 * @throws IOException
	 */
	public static void pushStream(InputStream is, OutputStream os) throws IOException {
		byte[] bytes = new byte[1024];
		int len = 0;
		try {
			while ((len = is.read(bytes)) > 0) {
				os.write(bytes, 0, len);
			}
			os.flush();
		} finally {
			if (null != is)
				is.close();
			if (null != os)
				os.close();
		}
	}

	public static boolean downloadFile(String path, HttpServletResponse response) {
		try {
			// path是指欲下载的文件的路径。
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			// 取得文件的后缀名。
			// String ext = filename.substring(filename.lastIndexOf(".") +
			// 1).toUpperCase();

			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			String codedFileName = URLEncoder.encode(filename, "UTF-8");
			response.addHeader("Content-Disposition", "attachment;filename=" + codedFileName);
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (IOException ex) {
			response.setContentType("text/html; charset=utf-8");
			try {
				PrintWriter writer = response.getWriter();
				writer.write("该文件找不到！");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return false;
			}
			ex.printStackTrace();
			return false;

		}
		return true;
	}
}